package com.newflypig.jblog.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 *	复写Spring框架中的 PropertyPlaceholderConfigurer
 *	赋予其读取加密字符串的功能
 *	@author newflypig
 *	time：2015年12月5日
 *
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		System.out.println("=================EncryptPropertyPlaceholderConfigurer setting successful!==================");	
        /**
         * 遍历key，通过key遍历value，对value进行正则匹配
         * 将匹配的值删"ENC(",再删")",继续对剩下的字符串进行DES解密
         */
		String filePath  = props.getProperty("jblog.token.filepath");
		String secretKey = this.getSecretKey(filePath); 
		
		if(secretKey == null){
			System.out.println("无法读取数据库加密文件,文件地址应该位于：" + filePath);
			return;
		}
		
        Set<Object> keys=props.keySet();
        for(Object o:keys){
        	String key = (String)o;
        	String value = props.getProperty(key);
        	
            if (value != null && value.matches("ENC\\([\\w+=/]+\\)")) {            	
                props.setProperty(key, DESUtil.decryptString(secretKey, value.substring(4,value.length()-1)));              
            }
        }
        
		super.processProperties(beanFactoryToProcess, props);
	}
	
	private String getSecretKey(String filePath){
		StringBuffer keyBuffer = new StringBuffer();
		try{
			InputStream is = new FileInputStream(filePath);
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = reader.readLine();
			while(line != null){
				keyBuffer.append(line);
				line = reader.readLine();
			}
			reader.close();
			is.close();
		}catch(Exception e){
			return null;
		}
		
		return keyBuffer.toString();
	}
}
